package mweb

import (
	"fmt"
	"gitee.com/dennis-mxx/mxx-core-v2/mdb"
	"gitee.com/dennis-mxx/mxx-core-v2/menv"
	"gitee.com/dennis-mxx/mxx-core-v2/mredis"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/sessions"
)

var store sessions.Store

func InitSession() {
	config := menv.Environment.Gin
	if config.Session == "" {
		config.Session = "cookie"
	}
	if config.SessionId == "" {
		config.SessionId = "sessionId"
	}
	if config.SessionSecret == "" {
		config.SessionSecret = "v0XqbECSxbhMVocsJLaYPGabE7236Agu"
	}
	switch config.Session {
	case "cookie":
		store = sessions.NewCookieStore([]byte(config.SessionSecret))
		break
	case "file":
		if config.SessionFile == "" {
			panic("session is file ,sessionFile is necessary")

		}
		store = sessions.NewFilesystemStore(config.SessionFile, []byte(config.SessionSecret))
		break
	case "redis":
		store = NewRedisStore(mredis.RedisClient, menv.Environment.ServerName, []byte(config.SessionSecret))
		break
	case "mysql":
		store = NewMysqlStore(mdb.Engine, menv.Environment.ServerName, []byte(config.SessionSecret))
		break
	case "sqlite":
		store = NewMysqlStore(mdb.Engine, menv.Environment.ServerName, []byte(config.SessionSecret))
		break
	default:
		panic(fmt.Sprintf("init session store failure ,  unsupported session type [%s]", config.Session))
	}
}

// SessionCtx
// Stx 此处是获取session 的前置句柄，如需要对session进行安全验证操作请在初始化完成后覆盖
type SessionCtx interface {
	GetSession() (*sessions.Session, error)
	Save()
}

type SessionCtxDefault struct {
	ctx       *gin.Context
	session   *sessions.Session
	sessionId string
}

func (domain *SessionCtxDefault) GetSession() (*sessions.Session, error) {
	ctx := domain.ctx
	if domain.session != nil {
		return domain.session, nil
	} else {
		s, err := store.Get(ctx.Request, domain.sessionId)
		domain.session = s
		return s, err
	}
}
func (domain *SessionCtxDefault) Save() {
	if domain.session != nil {
		err := domain.session.Save(domain.ctx.Request, domain.ctx.Writer)
		if err != nil {
			panic(err)
		}
	}
}
